package com.speedchina.permission.service.sys.impl;

import com.speedchina.framework.base.TService;
import com.speedchina.permission.dao.sys.DepartmentDao;
import com.speedchina.permission.domain.sys.entity.Department;
import com.speedchina.permission.service.sys.DepartmentService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * 基础组织结构表【逻辑删除时，下级节点批量变更】 服务层实现类
 * @author hank
 * @date 2021-05-19 14:12:48
 */
@Service
public class DepartmentServiceImpl extends TService<DepartmentDao, Department> implements DepartmentService {

//    @Override
//    public boolean saveOrUpdate4AutoGenId(Department entity) {
//        return super.saveOrUpdate4AutoGenId(entity);
//    }

    @Override
    public boolean deleteBatch(List<Serializable> ids) {
        // 考虑1： 删除时（逻辑删），把所有涉及到的 子节点 也一同查询出来，做统一 update 操作
        // 考虑2： 物理删除处理[目前做法]
        // 逻辑处理： 查询所有节点，在内存里 递归查找 所有子节点
        List<Department> all = this.queryList(new Department());
        Set<Serializable> childrenIds = new HashSet<>();
        ids.stream().forEach(id -> {
            this.findChildren(childrenIds, all, String.valueOf(id));
        });
        ids.addAll(new ArrayList<>(childrenIds));
        return super.deleteBatch(ids);
    }

    private void findChildren(Set<Serializable> childrenIds, List<Department> allData, String parentId) {
        allData.stream().forEach(department -> {
            if(parentId.equals(department.getParentId())) {
                childrenIds.add(department.getId());
                findChildren(childrenIds, allData, department.getId());
            }
        });
    }
}